﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class ContentController : Base
    {
        private readonly ArticleService _articleService;
        private readonly ArticleCateService _articleCateService;
        private readonly ConfigService _configService;
        private readonly AttmentService _attment;
        private readonly LogService _logService;
        public ContentController(ArticleService articleService, ArticleCateService articleCateService,
            LogService logService, AttmentService attmentService, ConfigService configService)
        {
            _articleService = articleService;
            _articleCateService = articleCateService;
            _configService = configService;
            _attment = attmentService;
            _logService = logService;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="searchcid">用于判断是否搜索CID</param>
        /// <param name="keyword"></param>
        /// <param name="stat">2 为所有内容 1 已经审核  0 草稿</param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="json">判断是否获取列表  1  0</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> IndexAsync(int cid, string keyword, int? searchcid, int stat = 2, int page = 1, int limit = 15, int json = 0)
        {
            ViewAdminUser adminUser = await UserClaims();
            int adminGid = adminUser.Gid;
            int adminUid = adminUser.Gid != 1 ? adminUser.Id : 0;//超级管理员显示全部数据

            if (json == 1)
            {
                int? newCid = searchcid > 0 || searchcid == 0 ? searchcid : cid;
                var pagedList = await _articleService.GetListByCidAdminAsync(newCid, page, limit, adminUid, keyword, stat);
                return Json(new { code = 0, count = pagedList.TotalItems, data = pagedList.Items });
            }
            ViewBag.cid = cid;
            ViewBag.catelist = await _articleCateService.GetCategoryListAsync(adminGid, 1);
            return View();

        }

        public async Task<IActionResult> AddOrEditAsync(int id, int edit = 0, int cid = 0)
        {
            if (edit == 1)
            {
                EditArticleAndContent data = await _articleService.GetEditAsync(id);
                List<ViewAttment> attments = null;
                if (!string.IsNullOrEmpty(data.Attments))
                    attments = await _attment.GetListAsync(data.Attments);
                return Json(new { status = 1, data, attments = attments });
            }
            //附件信息
            EditConfigSiteInfo configSiteInfo = await _configService.GetByNameAsync();
            ViewBag.fileExts = configSiteInfo.FileExt;
            ViewBag.fileSize = configSiteInfo.FileSize;
            //栏目信息
            ViewAdminUser adminUser = await UserClaims();
            ViewBag.articleCateData = await _articleCateService.GetCategorySelectListItemsAsync(adminUser.Gid, 1);
            ViewBag.cid = cid;
            //内容信息
            ViewBag.id = id;
            ViewBag.uid = adminUser.Id;
            return View();

        }

        [HttpPost, ActionName("CreatePost")]
        [XssFieldFilter]//防Xss
        public async Task<IActionResult> CreatePostAsync(EditArticleAndContent articlePost)
        {
            if (ModelState.IsValid)
            {
                ViewAdminUser adminUser = await UserClaims();

                Article article = articlePost.AsArticle();
                article.Uid = adminUser.Id;
                article.Gid = adminUser.Gid;

                Article articleRes = await _articleService.InsertArticleAndContentAsync(article, articlePost.AsArticleContent());

                if (articleRes.Id > 1)
                {
                    await _logService.InsertLogSqlAsync(await UserInfoAsync(), "新增内容 Id: " + articleRes.Id);
                    return Json(new { status = 1, msg = "新增成功！", cid = articleRes.Cid });
                }
                else
                    return Json(new { status = 0, msg = "新增失败！" });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { result = 0, msg = error });
            }
        }


        [HttpPost, ActionName("EditPost")]
        [XssFieldFilter]//防Xss
        public async Task<IActionResult> EditPostAsync(EditArticleAndContent articlePost)
        {
            if (ModelState.IsValid)
            {
                int x = await _articleService.UpdateArticleAndContentAsync(articlePost.AsArticle(), articlePost.AsArticleContent());
                if (x > 0)
                {
                    await _logService.InsertLogSqlAsync(await UserInfoAsync(), "修改内容 ID：" + articlePost.Id);
                    return Json(new { status = 1, msg = "修改成功！", cid = articlePost.Cid });
                }
                else
                {
                    return Json(new { status = 0, msg = "修改失败！" });
                }
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }

        public async Task<IActionResult> SwitchStatus(int id, int status, string att)
        {
            if (await _articleService.UpdateArticleAttAsync(id, status, att) > 0)
            {
                await _logService.InsertLogSqlAsync(await UserInfoAsync(), "设置属性 ID：" + id);
                return Json(new { status = 1, msg = "设置成功！" });
            }
            else
                return Json(new { status = 0, msg = "设置失败！" });
        }

        public async Task<IActionResult> Delete(int id)
        {
            if (await _articleService.DelArticleAndContentAsync(id) > 0)
            {
                await _logService.InsertLogSqlAsync(await UserInfoAsync(), "删除内容 ID：" + id);
                return Json(new { status = 1, msg = "删除成功！", url = "/Admin/Content/Index" });
            }
            else
                return Json(new { status = 0, msg = "删除失败！" });
        }
    }
}
